package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.wemedia.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.web-site}")
    String website;

    @Value("${file.oss.prefix}")
    String prefix;


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;


    /**
     * 素材收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id,short type) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材信息不存在");
        }
        //获取当前用户信息
        Integer userId = user.getId();
        if (!wmMaterial.getUserId().equals(userId)){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"用户只能收藏自己的素材");
        }
        wmMaterial.setIsCollection(type);
        updateById(wmMaterial);
//        update(Wrappers.<WmMaterial>lambdaUpdate()  // 如果只想修改指定字段 可以使用此方法
//                .set(WmMaterial::getIsCollection,type)
//                .eq(WmMaterial::getId,id)
//                .eq(WmMaterial::getUserId,uid));
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPic(Integer id) {
        // 1 参数校验
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if(count > 0){
            CustException.cust( AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        // 删除素材库
        removeById(id);
        // 删除图片OSS
        fileStorageService.delete(wmMaterial.getUrl());
        // 3 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //1. 参数校验
        dto.checkParam();
        if (dto==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();

        //是否收藏
        if (dto.getIsCollection() != null&&dto.getIsCollection()==1){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //用户ID查询
        queryWrapper.eq(WmMaterial::getUserId,user.getId());

        //按时间降序排序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> pageParam = new Page<>(dto.getPage(),dto.getSize());

        IPage<WmMaterial> resultPage = page(pageParam, queryWrapper);

        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(website+record.getUrl());
        }
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal(),records);

        return pageResponseResult;
    }


    /**
     * 上传图片接口
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验
        if (multipartFile==null||multipartFile.getSize()==0) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"上传素材不能为空");
        }

        // 当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //图片格式校验
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileFormat(originalFilename)){
            CustException.cust(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }

        //2. 上传到OSS
        String fileId=null;
        try {
        //生成新的UUID文件名
        String fileName = UUID.randomUUID().toString().replace("-","");

        //获取源文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

         fileId = fileStorageService.store(prefix, fileName + suffix, multipartFile.getInputStream());
            log.info("阿里云OSS 文件 fileId: {}",fileId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"服务器繁忙请稍后重试");
        }
        // 3 封装数据并保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection(WemediaConstants.CANCEL_COLLECT_MATERIAL);
        wmMaterial.setType((short)0);//图片类型
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 校验文件格式后缀
     * @param path
     * @return
     */
    private boolean checkFileFormat(String path) {
        if(StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if(path.endsWith(suffix)){
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }
}
